package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.BFDetailReport;
import Models.BFReport;

public class BFReportPresenter extends AbstractPresenter<BFReport> {
	final String SINGLEITEM = "bfReport";
	final String MULTIITEM = "bFReports";
	
	public ArrayList<BFReport> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public BFReport tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public BFReport createItemFromJSONObject(JSONObject jsonObject){
		BFReport item = new BFReport();
		try{
			item.setRsBeerID(jsonObject.getInt("beerID"));
			item.setRsBeerName(jsonObject.getString("beerName"));
			item.setRsBrewDate(getDateFromString(jsonObject.getString("brewDate")));
			item.setRsDueDate(getDateFromString(jsonObject.getString("dueDate")));
			item.setRsVol(jsonObject.getDouble("vol"));
			
			//Set Documents Collection
			ArrayList<BFDetailReport> details = new ArrayList<BFDetailReport>();
			if(!jsonObject.isNull("details")){
				Object itm = jsonObject.get("details");
				BFDetailReportPresenter presenter = new BFDetailReportPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						details.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					details.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setDetails(details);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(BFReport item){
		try{
			JSONObject json = new JSONObject();
			json.put("beerID", item.getRsBeerID());
			json.put("beerName", item.getRsBeerName());
			json.put("brewDate", getDate(item.getRsBrewDate()));
			json.put("dueDate", getDate(item.getRsDueDate()));
			json.put("vol", item.getRsVol());
			
			//Create Doc Collection
			if(item.getDetails()!=null){
				BFDetailReportPresenter presenter = new BFDetailReportPresenter();
				if(item.getDetails().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getDetails().size(); i++){
						jsonArray.put(presenter.createJSON(item.getDetails().get(i)));
					}
					json.put("details", jsonArray);
				}
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public BFReport getEmptyEntity(){
		BFReport entity = new BFReport();
		return entity;
	}
}
